package com.zmytest.service.impl;

import com.zmytest.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created on 2018/12/21.
 *
 * @author zhangmingyu
 */
@Service
@Slf4j
public class SessionServiceImpl implements SessionService {

    @Value("${session.expire-time}")
    private int sessionExpireTime;

    @Override
    public void create(String key, Object value) {
        HttpSession session = getHttpSession();
        session.setAttribute(key,value);
        session.setMaxInactiveInterval(sessionExpireTime);
        log.info("create session key [{}], value [{}]",key,value);
    }

    @Override
    public Object get(String key) {
        return getHttpSession().getAttribute(key);
    }

    @Override
    public void delete(String key) {
        getHttpSession().removeAttribute(key);
    }

    private HttpSession getHttpSession(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest().getSession();
    }
}
